import 'reflect-metadata';
import { createConnection, getManager } from 'typeorm';
import Koa from 'koa';
import Router from 'koa-router';
import bodyParser from 'koa-body';
import { User } from './entity/User';
import { Post } from './entity/Post';
var cors = require('koa2-cors');

const app = new Koa();
const router = new Router();
app.use(cors());
app.use(bodyParser());
// 连接到数据库
createConnection().then(async (connection) => {
  const userRepository = connection.getRepository(User);
  const postRepository = connection.getRepository(Post);

  // 获取所有用户
  router.get('/users', async (ctx) => {
    const users = await userRepository.createQueryBuilder("user").getMany();
    ctx.body = users;
  });

  // 创建用户
  router.post('/users', async (ctx) => {
    const userData = ctx.request.body;
    const user = userRepository.create(userData);
    await userRepository.save(user);
    ctx.status = 200;
    ctx.body = user;
  });


  // 获取单个用户
  router.get('/users/:id', async (ctx) => {
    const userId = parseInt(ctx.params.id, 10);

    if (isNaN(userId)) {
      ctx.status = 400;
      ctx.body = 'Invalid user ID';
      return;
    }
    const user = await userRepository.createQueryBuilder("user")
      .where("user.id = :id", { id: userId })
      .getOne();
    if (!user) {
      ctx.status = 404;
      ctx.body = 'User not found';
    } else {
      ctx.body = user;
    }
  });

  // 删除用户
  router.delete('/users/:id', async (ctx) => {
    const userId = parseInt(ctx.params.id, 10);

    if (isNaN(userId)) {
      ctx.status = 400;
      ctx.body = 'Invalid user ID';
      return;
    }

    const user = await userRepository.findOne(userId);

    if (!user) {
      ctx.status = 404;
      ctx.body = 'User not found';
      return;
    }

    // 删除用户
    await userRepository.remove(user);

    ctx.status = 200; // 204 表示删除成功，没有响应内容
    ctx.body = userId
  });

  // 编辑用户
  router.put('/users/:id', async (ctx) => {
    const userId = parseInt(ctx.params.id, 10);

    if (isNaN(userId)) {
      ctx.status = 400;
      ctx.body = 'Invalid user ID';
      return;
    }

    const user = await userRepository.findOne(userId);

    if (!user) {
      ctx.status = 404;
      ctx.body = 'User not found';
      return;
    }

    // 更新用户数据
    const userData = ctx.request.body;
    userRepository.merge(user, userData);
    const updatedUser = await userRepository.save(user);

    ctx.body = updatedUser;
  });

  // ================================== 帖子相关接口 ==========================

  // 获取所有帖子
  router.get('/posts', async (ctx) => {
    const comments = await postRepository.createQueryBuilder("post")
    .leftJoinAndSelect('post.user', 'user') // 使用leftJoinAndSelect来获取关联的user
    .getMany();
    ctx.body = comments;
  });
  // 获取单个帖子
  router.get('/posts/:id', async (ctx) => {
    const postId = parseInt(ctx.params.id, 10);

    if (isNaN(postId)) {
      ctx.status = 400;
      ctx.body = 'Invalid post ID';
      return;
    }
    const post = await postRepository.createQueryBuilder("post")
      .where("post.id = :id", { id: postId })
      .getOne();
    if (!post) {
      ctx.status = 404;
      ctx.body = 'post not found';
    } else {
      ctx.body = post;
    }
  });

  // 创建帖子
  router.post('/posts', async (ctx) => {
    // 创建一个新的 Post 对象
    const post = new Post();
    const postData = ctx.request.body;
    console.log('postData', postData)
    post.title = postData.title;
    post.content = postData.content;
    console.log('postData.userId', postData.userId)

    const user = await userRepository.findOne(postData.userId);

    if (!user) {
      ctx.status = 404;
      ctx.body = 'User not found';
      return;
    }
    // 将 User 对象分配给 Post 的 user 属性
    post.user = user;

    // 保存 Post 对象
    const postRepository = getManager().getRepository(Post);
    const savedPost = await postRepository.save(post);

    ctx.status = 200;
    ctx.body = savedPost;
  });

  // 删除
  router.delete('/posts/:id', async (ctx) => {
    const postId = parseInt(ctx.params.id, 10);

    if (isNaN(postId)) {
      ctx.status = 400;
      ctx.body = 'Invalid posts ID';
      return;
    }

    const post = await postRepository.findOne(postId);

    if (!post) {
      ctx.status = 404;
      ctx.body = 'posts not found';
      return;
    }

    // 删除
    await postRepository.remove(post);

    ctx.status = 200; // 204 表示删除成功，没有响应内容
    ctx.body = postId
  });

  // 编辑
  router.put('/posts/:id', async (ctx) => {
    const postId = parseInt(ctx.params.id, 10);

    if (isNaN(postId)) {
      ctx.status = 400;
      ctx.body = 'Invalid post ID';
      return;
    }

    const post = await postRepository.findOne(postId);

    if (!post) {
      ctx.status = 404;
      ctx.body = 'Post not found';
      return;
    }

    // 更新
    const postData = ctx.request.body;
    postRepository.merge(post, postData);
    const updatedPost = await postRepository.save(post);

    ctx.body = updatedPost;
  });

  app.use(router.routes()).use(router.allowedMethods());
  app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
  });
});



